﻿--	Copyright (C) 2007 by Fritos
--	
--	This program is free software; you can redistribute it and--or modify
--	it under the terms of the GNU General Public License as published by
--	the Free Software Foundation; either version 2 of the License, or
--	(at your option) any later version.
--	
--	This program is distributed in the hope that it will be useful,
--	but WITHOUT ANY WARRANTY; without even the implied warranty of
--	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--	GNU General Public License for more details.
--	
--	You should have received a copy of the GNU General Public License
--	along with this program; if not, write to the Free Software Foundation, Inc.,
--	59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

Dailies = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceEvent-2.0", "FuBarPlugin-2.0", "AceDB-2.0", "Sink-1.0")

local Tablet = AceLibrary("Tablet-2.0")
local Dewdrop = AceLibrary("Dewdrop-2.0")
local Crayon = AceLibrary("Crayon-2.0")
local Quixote = AceLibrary("Quixote-1.0")
local Deformat = AceLibrary("Deformat-2.0")
local Abacus = AceLibrary("Abacus-2.0")
local L = AceLibrary("AceLocale-2.2"):new("Dailies")

-- Hack counter to pull Tradeskills only once
TradeskillCounter = 0
-- Scheduled reset time for dailies (i.e 3 am Server Time)
DailiesReset = 3

local RepFactionsHolder = {
		["BGPvP"] = 0,
		["Cooking"] = 0,
		["Holiday"] = 0,
		["HInstance"] = 0,
		["NInstance"] = 0,
		["Netherwing"] = nil,
		["Ogri'la"] = nil,
		["Sha'tari Skyguard"] = nil,
		["Honor Hold"] = nil,
		["Thrallmar"] = nil,
}

-- Reputation Faction Colors
local RepFactionColors = {
	[0] = {r = 0.5, g = 0.5, b = 0.5},		-- Unknown
	[1] = {r = 0.55, g = 0, b = 0},			-- hated
	[2] = {r = 1, g = 0, b = 0},			-- hostile
	[3] = {r = 1, g = 0.55, b = 0},			-- unfriendly
	[4] = {r = 0.75, g = 0.75, b = 0.75},	-- neutral
	[5] = {r = 1, g = 1, b = 1},			-- friendly
	[6] = {r = 0, g = 1, b = 0},			-- honored
	[7] = {r = 0.25, g = 0.4, b = 0.9},		-- revered
	[8] = {r = 0.6, g = 0.2, b = 0.8},		-- exalted	
}

 -- Coverter from RGB to HEX
local function RGBPercToHex(r, g, b)
	r = r <= 1 and r >= 0 and r or 0
	g = g <= 1 and g >= 0 and g or 0
	b = b <= 1 and b >= 0 and b or 0
	return string.format("%02x%02x%02x", r*255, g*255, b*255)
end
 
function Dailies:OnInitialize()
englishFaction, _ = UnitFactionGroup("Player")
PlayerRace, _ = UnitRace("Player");

Dailies.hasIcon  = true;
Dailies.title = L["DAILIES_TITLE"];
Dailies.hideMenuTitle = true;
Dailies.cannotDetachTooltip = false;
Dailies:RegisterDB("DailiesDB");
Dailies.clickableTooltip = true;

DailiesGroups = {
	["Honor Hold"] = {group = "Honor Hold", title = "Honor Hold ["..Crayon:Green(L["WORLD_PVP"]).."]", ValueMax = 1},
	["Thrallmar"] = {group = "Thrallmar", title = "Thrallmar ["..Crayon:Green(L["WORLD_PVP"]).."]", ValueMax = 1},
	["BGPvP"] = {group = "BGPvP", title = L["TITLE_BATTLEGROUNDS"] .." ["..Crayon:Green(L["DAILY_RANDOM"]).."]", ValueMax = 1},
	["Cooking"] = {group ="Cooking", title = L["TITLE_COOKING"] .. " ["..Crayon:Green(L["DAILY_RANDOM"]).."]", ValueMax = 1},
	["Holiday"] = {group ="Holiday", title = L["TITLE_HOLIDAY"] .. " ["..Crayon:Green(L["TITLE_SEASONAL"]).."]", ValueMax = 1},
	["HInstance"] = {group ="HInstance", title = L["TITLE_HINSTANCE"] .. " ["..Crayon:Green(L["DAILY_RANDOM"]).."]", ValueMax = 1},
	["NInstance"] = {group ="NInstance", title = L["TITLE_NINSTANCE"] .." [" .. Crayon:Green(L["DAILY_RANDOM"]) .. "]", ValueMax = 1},
	["Netherwing"] = {group ="Netherwing", title = "Netherwing", ValueMax = 8},
	["Ogri'la"] = {group ="Ogri'la", title = "Ogri'la", ValueMax = 2},
	["Sha'tari Skyguard"] = {group ="Sha'tari Skyguard", title = "Sha'tari Skyguard", ValueMax = 4}
}

if englishFaction == "Alliance" then
	DailyQuestsList["Hellfire Fortifications"] = {icon = "Interface\\Icons\\INV_Misc_Token_HonorHold", group = "Honor Hold", SID = 4, ["rep"] = {"Honor Hold:150"}, ["rewards"] = {"24579:3"}, gold = 11350}
	DailyQuestsList["Bark for the Barleybrews!"] = {icon = "Interface\\Icons\\INV_Belt_05", group = "Holiday", SID = 0, fact = "Alliance", dates = {starting = "10/02", ending = "10/16"}, ["rewards"] = {"33455:40"}}
	DailyQuestsList["Bark for the Thunderbrews!"] = {icon = "Interface\\Icons\\INV_Belt_05", group = "Holiday", SID = 0, fact = "Alliance", dates = {starting = "10/02", ending = "10/16"}, ["rewards"] = {"33455:40"}}
	BGHonor = "Interface\\Addons\\Dailies\\Icons\\Alliance.tga"
	
elseif englishFaction == "Horde" then
	DailyQuestsList["Hellfire Fortifications"] = {icon = "Interface\\Icons\\INV_Misc_Token_Thrallmar", group = "Thrallmar", SID = 4, ["rep"] = {"Thrallmar:150"}, ["rewards"] = {"24581:3"}, gold = 11350}
	DailyQuestsList["Bark for Drohn's Distillery!"] = {icon = "Interface\\Icons\\INV_Belt_05", group = "Holiday", SID = 0, fact = "Horde", dates = {starting = "10/02", ending = "10/16"}, ["rewards"] = {"33455:40"}}
	DailyQuestsList["Bark for T'chali's Voodoo Brewery!"] = {icon = "Interface\\Icons\\INV_Belt_05", group = "Holiday", SID = 0, fact = "Horde", dates = {starting = "10/02", ending = "10/16"}, ["rewards"] = {"33455:40"}}
	BGHonor = "Interface\\Addons\\Dailies\\Icons\\Horde.tga"
end

Dailies:RegisterDefaults('profile', {
	QuestsVisible = true,
	hideDetails = {
		["Honor Hold"] = true,
		["Thrallmar"] = true,
		["BGPvP"] = true,
		["Cooking"] = true,
		["Holiday"] = true,
		["HInstance"] = true,
		["NInstance"] = true,
		["Netherwing"] = true,
		["Ogri'la"] = true,
		["Sha'tari Skyguard"] = true,
		},
})

Dailies:RegisterDefaults('char', {
	DailyQuestsAccepted = {},
	DailyQuestsCompleted = {},
	DailyQuestsObjectives = {},
	TooltipPlacement = "Right",
	LocationShow = true,
	HideHints = false,
	Filters = {
		["Honor Hold"] = false,
		["Thrallmar"] = false,
		["BGPvP"] = false,
		["Cooking"] = false,
		["Holiday"] = false,
		["HInstance"] = false,			
		["NInstance"] = false,
		["Netherwing"] = false,
		["Ogri'la"] = false,
		["Sha'tari Skyguard"] = false,
	},
	GroupValues = {
		["BGPvP"] = 0,
		["Cooking"] = 0,
		["Holiday"] = 0,
		["HInstance"] = 0,			
		["NInstance"] = 0,
		["Netherwing"] = 0,
		["Ogri'la"] = 0,
		["Sha'tari Skyguard"] = 0,
		["Honor Hold"] = 0,
		["Thrallmar"] = 0,
	},
})

Dailies:RegisterEvent("CHAT_MSG_SYSTEM", "DailiesQuest_Tracker")
Dailies:RegisterEvent("UNIT_QUEST_LOG_CHANGED", "DailiesUpdate")
Dailies:RegisterEvent("PLAYER_ALIVE", "PLAYER_ALIVE")
Dailies:RegisterEvent("ADDON_LOADED", "ADDON_LOADED")
Dailies:RegisterEvent("Quixote_Quest_Complete", "QuestObjectives")
Dailies:RegisterEvent("ZONE_CHANGED", "ZONE_CHANGED")
Dailies:RegisterEvent("ZONE_CHANGED_NEW_AREA", "ZONE_CHANGED")
	
Dailies:PLAYER_ALIVE();
StaticPopupDialogs["ABANDON_QUEST"].OnAccept = function() Dailies:AbandonedQuest(GetAbandonQuestName()); AbandonQuest(); PlaySound("igQuestLogAbandonQuest"); end
StaticPopupDialogs["ABANDON_QUEST_WITH_ITEMS"].OnAccept = function() Dailies:AbandonedQuest(GetAbandonQuestName()); AbandonQuest(); PlaySound("igQuestLogAbandonQuest"); end
end

-- Check to see if USER wants unfolding of groups and unfold when necessary
function Dailies:ZONE_CHANGED()
	local DailiesZoneName = GetRealZoneText(); local DailiesSubZoneName = GetSubZoneText();
	local DailiesInInstance, DailiesInstanceType = IsInInstance(); local DailiesDifficulty = GetInstanceDifficulty()
	
	if self.db.char.LocationShow == true then
		for GroupName, GroupText in pairsByKeys (DailiesGroups) do
			self.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] = true
		end
		
		if DailiesZoneName == "Shattrath City" and DailiesSubZoneName == "Lower City" then
			self.db.profile.hideDetails["Cooking"] = false
			self.db.profile.hideDetails["NInstance"] = false
			self.db.profile.hideDetails["HInstance"] = false
			self.db.profile.hideDetails["BGPvP"] = false
		end
		
		if DailiesZoneName == "Shadowmoon Valley" then
			self.db.profile.hideDetails["Netherwing"] = false
		end
		
		if DailiesZoneName == "Blade's Edge Mountains" then
			self.db.profile.hideDetails["Ogri'la"] = false
			self.db.profile.hideDetails["Cooking"] = false
			self.db.profile.hideDetails["Sha'tari Skyguard"] = false
		end

		if DailiesZoneName == "Nagrand" then
				self.db.profile.hideDetails["Cooking"] = false
			if DailiesSubZoneName == "The Twilight Ridge" then
				self.db.profile.hideDetails["Netherwing"] = false
			end
		end		
 
		if DailiesZoneName == "Terokkar Forest" then
			local LocValues = {"Blackwind Landing", "Blackwind Valley", "Skettis", "Blackwind Lake", "Terokk's Rest", "Veil Ala'rak", "Lower Veil Shil'ak", "Upper Veil Shil'ak", "Veil Harr'ik"}
			for index, value in pairs (LocValues) do
				if DailiesSubZoneName == value then
					self.db.profile.hideDetails["Sha'tari Skyguard"] = false
					self.db.profile.hideDetails["Cooking"] = false
				end
			end
			LocValues = nil
		end
		
		if DailiesZoneName == "Netherstorm" then
			local LocValues = {"Eco-Dome Midrealm", "Eco-Dome Farfield"}
			for index, value in pairs (LocValues) do
				if DailiesSubZoneName == value then
					self.db.profile.hideDetails["Cooking"] = false
				end
			end
			LocValues = nil
		end
		
		if DailiesZoneName == "Hellfire Peninsula" then
			self.db.profile.hideDetails["Honor Hold"] = false
		end

		if DailiesInInstance and DailiesInstanceType == "pvp"  then
			self.db.profile.hideDetails["BGPvP"] = false
		end		
		
		if DailiesInInstance then
			if DailiesInstanceType == "party" and DailiesDifficulty == 2 then
				self.db.profile.hideDetails["NInstance"] = false
				self.db.profile.hideDetails["HInstance"] = false
			end
		else
			if DailiesInstanceType == "party" and DailiesDifficulty == 1 then
				self.db.profile.hideDetails["NInstance"] = false
			end
		end
		self:UpdateTooltip()
	end
end

-- Check to see if Fubar is loaded
function Dailies:ADDON_LOADED(arg1)
	if arg1 == "LibFuBarPlugin-3.0" then
		LibRockFuBar = true
	end
 end
 
 -- Hack for when someone Abandons a daily, so we can reset it in the tooltip
function Dailies:AbandonedQuest()
	local AbandonedName = GetAbandonQuestName();
	for index, value in pairs (Dailies.db.char.DailyQuestsAccepted) do
		if index == AbandonedName then
			Dailies.db.char.DailyQuestsAccepted[index] = nil;
			Dailies.db.char.DailyQuestsObjectives[index] = nil;
		end
	end
end

-- Table sorter
function pairsByKeys (t, f)
	local TempHolder = {}
	for n in pairs (t) do 
		table.insert (TempHolder, n) 
	end
	table.sort (TempHolder, f)
	local i = 0
	return function ()
	i = i + 1
	return TempHolder[i], t[TempHolder[i]]
	end
end

-- Checks to see if the USER has finished all the objectives in a quest
function Dailies:QuestObjectives(QuestNameObjectives, QID)
	if Dailies.db.char.DailyQuestsAccepted[QuestNameObjectives] then
		Dailies.db.char.DailyQuestsObjectives[QuestNameObjectives] = L["QUEST_TURN_IN"]
	end
end

-- Check for EVENT triggers
function Dailies:DailiesQuest_Tracker(msg)
	local QuestName = Deformat(msg, ERR_QUEST_COMPLETE_S)
	local QuestNameAccepted = Deformat(msg, ERR_QUEST_ACCEPTED_S)
	local DailiesQuestReset = Deformat(msg, DAILY_QUESTS_REMAINING)
	
	if DailiesQuestReset == GetMaxDailyQuests() then
		self.db.char.DailyQuestsCompleted = {};
		self.db.char.GroupValues = {
			["BGPvP"] = 0,
			["Cooking"] = 0,
			["Holiday"] = 0,
			["HInstance"] = 0,			
			["NInstance"] = 0,
			["Netherwing"] = 0,
			["Ogri'la"] = 0,
			["Sha'tari Skyguard"] = 0,
			["Honor Hold"] = 0,
			["Thrallmar"] = 0,			
		}
		Dailies:DailiesUpdate()
	end
	
	for QuestAcceptedIndex, QuestAcceptedValue in pairs(DailyQuestsList) do
		if (QuestNameAccepted == QuestAcceptedIndex) then
			local QuestHour, QuestMinute = GetGameTime(); local QuestPM = floor(QuestHour / 12) == 1; QuestHour = mod(QuestHour, 12); if QuestHour == 0 then QuestHour = 12 end;
			QuestTimeAccepted = string.format("%d" .. Crayon:Gold(":") .. "%02d" .. Crayon:Gold(" %s"), QuestHour, QuestMinute, QuestPM and "PM" or "AM");
			Dailies.db.char.DailyQuestsAccepted[QuestNameAccepted] = QuestTimeAccepted
			Dailies:Pour(QuestNameAccepted .. " accepted at " .. QuestTimeAccepted, nil, nil, nil, nil, nil, "OUTLINE", nil, "NOTIFY", DailyQuestsList[QuestNameAccepted]["icon"])
		end
	end
	
	for QuestCompletedIndex, QuestCompletedValue in pairs(DailyQuestsList) do
		if (QuestName == QuestCompletedIndex) then
			local QuestHour, QuestMinute = GetGameTime(); local QuestPM = floor(QuestHour / 12) == 1; QuestHour = mod(QuestHour, 12); if QuestHour == 0 then QuestHour = 12 end;
			QuestTimeCompleted = string.format("%d" .. Crayon:Gold(":") .. "%02d" .. Crayon:Gold(" %s"), QuestHour, QuestMinute, QuestPM and "PM" or "AM");
			Dailies.db.char.DailyQuestsCompleted[QuestName] = QuestTimeCompleted; Dailies.db.char.DailyQuestsAccepted[QuestCompletedIndex] = nil; Dailies.db.char.DailyQuestsObjectives[QuestCompletedIndex] = nil
			Dailies:Pour(QuestName .. L["SCT_COMPLETED"] .. QuestTimeCompleted, nil, nil, nil, nil, nil, "OUTLINE", nil, "NOTIFY", DailyQuestsList[QuestName]["icon"])
			Dailies:QuestValue(QuestName);
		end
	end
	self:UpdateTooltip()
end

-- Holder and Counter for groups
function Dailies:QuestValue(QuestName)
	CookingValue = Dailies.db.char.GroupValues["Cooking"]
	if DailyQuestsList[QuestName]["group"] == "Cooking" then CookingValue = CookingValue + 1 end; Dailies.db.char.GroupValues["Cooking"] = CookingValue	

	HonorHoldValue = Dailies.db.char.GroupValues["Honor Hold"]
	if DailyQuestsList[QuestName]["group"] == "Honor Hold" then HonorHoldValue = HonorHoldValue + 1 end; Dailies.db.char.GroupValues["Honor Hold"] = HonorHoldValue
	
	ThrallmarValue = Dailies.db.char.GroupValues["Thrallmar"]
	if DailyQuestsList[QuestName]["group"] == "Thrallmar" then ThrallmarValue = ThrallmarValue + 1 end; Dailies.db.char.GroupValues["Thrallmar"] = ThrallmarValue		
		
	NetherwingValue = Dailies.db.char.GroupValues["Netherwing"]
	if DailyQuestsList[QuestName]["group"] == "Netherwing" then NetherwingValue = NetherwingValue + 1 end; Dailies.db.char.GroupValues["Netherwing"] = NetherwingValue

	OgrilaValue = Dailies.db.char.GroupValues["Ogri'la"]
	if DailyQuestsList[QuestName]["group"] == "Ogri'la" then OgrilaValue = OgrilaValue + 1 end; Dailies.db.char.GroupValues["Ogri'la"] = OgrilaValue
		
	SkyguardValue = Dailies.db.char.GroupValues["Sha'tari Skyguard"]
	if DailyQuestsList[QuestName]["group"] == "Sha'tari Skyguard" then SkyguardValue = SkyguardValue + 1 end; Dailies.db.char.GroupValues["Sha'tari Skyguard"] = SkyguardValue
	
	HolidayValue = Dailies.db.char.GroupValues["Holiday"]
	if DailyQuestsList[QuestName]["group"] == "Holiday" then HolidayValue = HolidayValue + 1 end; Dailies.db.char.GroupValues["Holiday"] = HolidayValue	

	BGPvPValue = Dailies.db.char.GroupValues["BGPvP"]
	if DailyQuestsList[QuestName]["group"] == "BGPvP" then BGPvPValue = BGPvPValue + 1 end; Dailies.db.char.GroupValues["BGPvP"] = BGPvPValue	

	NInstanceValue = Dailies.db.char.GroupValues["NInstance"]
	if DailyQuestsList[QuestName]["group"] == "NInstance" then NInstanceValue = NInstanceValue + 1 end; Dailies.db.char.GroupValues["NInstance"] = NInstanceValue	

	HInstanceValue = Dailies.db.char.GroupValues["HInstance"]
	if DailyQuestsList[QuestName]["group"] == "HInstance" then HInstanceValue = HInstanceValue + 1 end; Dailies.db.char.GroupValues["HInstance"] = HInstanceValue		
end

function Dailies:DailiesUpdate()
	DQMax = GetMaxDailyQuests();
	DQComplete = GetDailyQuestsCompleted();
	Dailies:UpdateText();
end

function Dailies:OnEnable()
	DQComplete = GetDailyQuestsCompleted();
	DQMax = GetMaxDailyQuests();
	
	if DQComplete == 0 then
		self.db.char.DailyQuestsCompleted = {};
		self.db.char.GroupValues = {
			["BGPvP"] = 0,
			["Cooking"] = 0,
			["Holiday"] = 0,
			["HInstance"] = 0,
			["NInstance"] = 0,			
			["Netherwing"] = 0,
			["Ogri'la"] = 0,
			["Sha'tari Skyguard"] = 0,
			["Honor Hold"] = 0,
			["Thrallmar"] = 0,
		}
	end
	
	hour, minute = GetGameTime();
	DQStartHour = hour;
	DQStartMiniute = minute;

	Dailies:UpdateText();
end

function Dailies:PLAYER_ALIVE()
	DQMax = GetMaxDailyQuests();
	DQComplete = GetDailyQuestsCompleted();
	-- Cycle through Tradeskills
	numSkills = GetNumSkillLines();
	if TradeskillCounter == 0 then
		for i=1, numSkills do
			skillName = GetSkillLineInfo(i);
			if skillName == "Herbalism" then
				DailiesGroups["Netherwing"]["ValueMax"] = DailiesGroups["Netherwing"]["ValueMax"] + 1
				hasHerbalism = "Herbalism";
			elseif skillName == "Mining" then
				DailiesGroups["Netherwing"]["ValueMax"] = DailiesGroups["Netherwing"]["ValueMax"] + 1
				hasMining = "Mining";
			elseif skillName == "Skinning" then
				DailiesGroups["Netherwing"]["ValueMax"] = DailiesGroups["Netherwing"]["ValueMax"] + 1
				hasSkinning = "Skinning";
			end
			TradeskillCounter = 1
		end
	end
	Dailies:UpdateText();
end

function Dailies:OnTextUpdate()
	DQColor = Crayon:GetThresholdHexColor(GetDailyQuestsCompleted(), GetMaxDailyQuests())
	Dailies:SetText(Crayon:Colorize(DQColor, GetDailyQuestsCompleted()) .."/".. Crayon:Green(GetMaxDailyQuests()));
	Dailies:SetIcon("Interface\\Addons\\Dailies\\Icons\\" .. (GetMaxDailyQuests() - GetDailyQuestsCompleted()) .. ".tga")
end

-- Dailies Quest Tracker options menu
function Dailies:OnMenuRequest(level, value, inTooltip)
    if not inTooltip or inTooltip then
		if level == 1 then
			-- Dailies Config Title
			Dewdrop:AddLine(
				'text', L["CONFIG"],
				'isTitle', true,
				'icon', "Interface\\Addons\\Dailies\\Icon.tga",
				'iconWidth', 12,
				'iconHeight', 12
			)
			
			-- Show All Dailies
			Dewdrop:AddLine(
				'text', L["CONFIG_SHOW_DAILIES"],
				'checked', self.db.profile.QuestsVisible,
				'func', function ()
					self.db.profile.QuestsVisible  = not self.db.profile.QuestsVisible ;
					if (self.db.profile.QuestsVisible  == true) then
						self.db.profile.QuestsVisible  = true;
					else
						self.db.profile.QuestsVisible  = false;
					end
					self:UpdateText();
				end,
				'tooltipTitle', L["CONFIG_SHOW_DAILIES"],
				'tooltipText', L["CONFIG_SHOW_DAILIES_DESC"]
			)
			
			-- HINTS
			Dewdrop:AddLine(
				'text', L["CONFIG_HINTS"],
				'checked', self.db.char.HideHints,
				'func', function ()
					self.db.char.HideHints  = not self.db.char.HideHints
				end,
				'tooltipTitle', L["CONFIG_HINTS"],
				'tooltipText', L["CONFIG_HINTS_DESC"]
			)
			
			-- Location unfold
			Dewdrop:AddLine(
				'text', L["CONFIG_LOCATION"],
				'checked', self.db.char.LocationShow,
				'func', function ()
					self.db.char.LocationShow  = not self.db.char.LocationShow
				end,
				'tooltipTitle', L["CONFIG_LOCATION"],
				'tooltipText', L["CONFIG_LOCATION_DESC"]
			)			

			-- Filters
			Dewdrop:AddLine(
				'text', L["CONFIG_FILTERS"],
				'hasArrow', true,
				'value', "Filters",
				'tooltipTitle', L["CONFIG_FILTERS"],
				'tooltipText', L["CONFIG_FILTERS_DESC"]
			)
			
			-- Tooltip Placement
			Dewdrop:AddLine(
				'text', L["CONFIG_TOOLTIP"],
				'hasArrow', true,
				'value', "Rewards",
				'tooltipTitle',  L["CONFIG_TOOLTIP"],
				'tooltipText', L["CONFIG_TOOLTIP_DESC"]
			)			
			
			-- Spacer
			Dewdrop:AddSeparator()
			
			-- Scrolling Combat Text Title
			Dewdrop:AddLine(
			'text', L["CONFIG_SCT"],
			'isTitle', true,
			'tooltipTitle', L["CONFIG_SCT"],
			'tooltipText', L["CONFIG_SCT_DESC"]
			)
			
		elseif level == 2 then
			if value == "Rewards" then
				Dewdrop:AddLine(
				'text', L["CONFIG_TOOLTIP_RIGHT"],
				'checked', self.db.char.TooltipPlacement == "Right",
				'func', function ()
					RightTooltip = true; LeftTooltip = nil; 
					self.db.char.TooltipPlacement = "Right"
				end,
				'isRadio', true
				)
				
				Dewdrop:AddLine(
				'text', L["CONFIG_TOOLTIP_LEFT"],
				'checked', self.db.char.TooltipPlacement == "Left",
				'func', function ()
					RightTooltip = nil; LeftTooltip = true; 
					self.db.char.TooltipPlacement = "Left"
				end,
				'isRadio', true
				)
			end

			if value == "Filters" then
				Dewdrop:AddLine(
				'text', L["TITLE_BATTLEGROUNDS"],
				'checked', self.db.char.Filters["BGPvP"],
				'func', function ()
					self.db.char.Filters["BGPvP"] = not self.db.char.Filters["BGPvP"]
				end,
				'isRadio', true
				)
				
				Dewdrop:AddLine(
				'text', L["TITLE_COOKING"],
				'checked', self.db.char.Filters["Cooking"],
				'func', function ()
					self.db.char.Filters["Cooking"] = not self.db.char.Filters["Cooking"]				
				end,
				'isRadio', true
				)

				Dewdrop:AddLine(
				'text', L["TITLE_HINSTANCE"],
				'checked', self.db.char.Filters["HInstance"],
				'func', function ()
					self.db.char.Filters["HInstance"] = not self.db.char.Filters["HInstance"]				
				end,
				'isRadio', true
				)
				
				Dewdrop:AddLine(
				'text', L["TITLE_HOLIDAY"],
				'checked', self.db.char.Filters["Holiday"],
				'func', function ()
					self.db.char.Filters["Holiday"] = not self.db.char.Filters["Holiday"]				
				end,
				'isRadio', true
				)
				
				-- Check if USER's faction is ALLIANCE to show filter
				if englishFaction == "Alliance" then
					Dewdrop:AddLine(
					'text', "Honor Hold",
					'checked', self.db.char.Filters["Honor Hold"],
					'func', function ()
						self.db.char.Filters["Honor Hold"] = not self.db.char.Filters["Honor Hold"]				
					end,
					'isRadio', true
					)
				end
				
				Dewdrop:AddLine(
				'text', L["TITLE_NINSTANCE"],
				'checked', self.db.char.Filters["NInstance"],
				'func', function ()
					self.db.char.Filters["NInstance"] = not self.db.char.Filters["NInstance"]				
				end,
				'isRadio', true
				)

				Dewdrop:AddLine(
				'text', "Netherwing",
				'checked', self.db.char.Filters["Netherwing"],
				'func', function ()
					self.db.char.Filters["Netherwing"] = not self.db.char.Filters["Netherwing"]				
				end,
				'isRadio', true
				)

				Dewdrop:AddLine(
				'text', "Ogri'la",
				'checked', self.db.char.Filters["Ogri'la"],
				'func', function ()
					self.db.char.Filters["Ogri'la"] = not self.db.char.Filters["Ogri'la"]				
				end,
				'isRadio', true
				)

				Dewdrop:AddLine(
				'text', "Sha'tari Skyguard",
				'checked', self.db.char.Filters["Sha'tari Skyguard"],
				'func', function ()
					self.db.char.Filters["Sha'tari Skyguard"] = not self.db.char.Filters["Sha'tari Skyguard"]				
				end,
				'isRadio', true
				)
				
				-- Check if USER's faction is HORDE to show filter
				if englishFaction == "Horde" then
					Dewdrop:AddLine(
					'text', "Honor Hold",
					'checked', self.db.char.Filters["Honor Hold"],
					'func', function ()
						self.db.char.Filters["Honor Hold"] = not self.db.char.Filters["Honor Hold"]				
					end,
					'isRadio', true
					)
				end				
			end
		end
	end
	self:UpdateTooltip()
end

function Dailies:OnTooltipUpdate()
	-- Cycle through the USER's known factions and hold them in a table to see if groups should be displayed
	for factionIndex = 1, GetNumFactions() do
	-- name, description, standingId, bottomValue, topValue, earnedValue, atWarWith, canToggleAtWar, isHeader, isCollapsed, isWatched = GetFactionInfo(factionIndex)
		FactionName, _, standingID, _, _, _, _, _, isHeader, isCollapsed, _ = GetFactionInfo(factionIndex)
		RepFactionsHolder[FactionName] = standingID
	end
	
	-- Dailies reset timer
	hour, minute = GetGameTime();
	if ( hour >= 0 ) and ( hour < DailiesReset) then
		if ( minute >= 0 ) then
			DQStartMinute = math.abs(60 - minute)
		end

		if ( DQStartMinute == 60 ) then
			DQStartMinute = 0
		else
			DQStartHour = math.abs(2 - hour)
		end
	end
	
	if ( hour == DailiesReset ) then
		DQStartHour = 24;
	end

	if ( hour >= DailiesReset ) and ( hour < 24 ) then
		if ( minute >= 0 ) then
			DQStartMinute = math.abs(60 - minute)
		end

		if ( DQStartMinute == 60 ) then
			DQStartMinute = 0
		else
			DQStartHour = math.abs(24 - hour + (DailiesReset - 1))
		end
	end

	-- How to display 'Hours' and 'Minutes'
	if DQStartHour > 1 then
		HourLength = L["LONG_HOUR"]
	else
		HourLength = L["SHORT_HOUR"]
	end

	if DQStartMinute > 1 then
		MinuteLength = L["LONG_MINUTE"]
	else
		MinuteLength = L["SHORT_MINUTE"]
	end

	if DQStartHour <= 0 then
		DailiesText = string.format(L["DAILIES_RESET"].. MinuteLength, DQStartMinute)
	elseif DQStartHour > 0 then
		if ( DQStartMinute == 0 ) then
			DailiesText = string.format(L["DAILIES_RESET"] .. HourLength, DQStartHour)
		else
			DailiesText = string.format(L["DAILIES_RESET"] .. HourLength .. " and " .. MinuteLength, DQStartHour, DQStartMinute)
		end
	end

	if ( DQComplete < DQMax ) then
		-- You can complete XX daily quests today
		AmountText = string.format(L["DAILIES_COUNT"], (GetMaxDailyQuests() - GetDailyQuestsCompleted()))
	else
		-- You cannot complete any more daily quests today
		AmountText = L["DAILIES_COMPLETE"]
	end
	
	cat = Tablet:AddCategory(
		'columns', 1,
		'showWithoutChildren', true,
		'hideBlankLine', true
	 )
	cat:AddLine(
		'text', DailesDATE,
		'textR', .5,
		'textG', .5,
		'textB', .5,
		'justify', "CENTER"
	)
	
		if self.db.char.DailyQuestsCompleted then
		for GroupName, GroupText in pairsByKeys (DailiesGroups) do
			if self.db.profile.QuestsVisible == true and self.db.char.Filters[GroupName] == false and RepFactionsHolder[GroupName] then
				MinColor = Crayon:GetThresholdHexColor(self.db.char.GroupValues[DailiesGroups[GroupName]["group"]], DailiesGroups[GroupName]["ValueMax"])
				cat = Tablet:AddCategory(
					'text', DailiesGroups[GroupName]["title"],
					'textR', 1, 'textG', 0.8, 'textB', 0,
					'text2', "[" .. Crayon:Colorize(MinColor, self.db.char.GroupValues[GroupName]) .. "/" .. Crayon:Green(DailiesGroups[GroupName]["ValueMax"]) .. "]",
					'text2R', 1, 'text2G', 0.8, 'text2B', 0,
					'columns', 2,
					'showWithoutChildren', true,
					'hideBlankLine', true,
					'func', function() self.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] = not self.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] end,
					'hasCheck', true,
					'checked', true,
					'checkIcon', self.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] and "Interface\\Buttons\\UI-PlusButton-Up" or "Interface\\Buttons\\UI-MinusButton-Up"
				)
				
				for index, value in pairsByKeys (DailyQuestsList) do
					if Dailies.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] == false then		
						if DailyQuestsList[index]["group"] == GroupName then
							if self.db.char.DailyQuestsObjectives[index] == L["QUEST_TURN_IN"] then RColor= 0; GColor= 1; BColor = 0; RIcon= 1; GIcon= 1; BIcon = 1; CompletedText = L["QUEST_TURN_IN"]
								elseif self.db.char.DailyQuestsCompleted[index] then RColor= 1; GColor= 1; BColor = 1; RIcon= 1; GIcon= 1; BIcon = 1; CompletedText = self.db.char.DailyQuestsCompleted[index]
								elseif self.db.char.DailyQuestsAccepted[index] then RColor= 0; GColor= 1; BColor = 0; RIcon= 1; GIcon= 1; BIcon = 1; CompletedText = L["QUEST_ACCEPTED"]
								elseif self.db.char.GroupValues[DailiesGroups[GroupName]["group"]] ==  DailiesGroups[GroupName]["ValueMax"] then RColor= 1; GColor= 0; BColor = 0; RIcon= 1; GIcon= 0; BIcon = 0; CompletedText = L["DAILIES_GROUP_MAX"]
								elseif GetDailyQuestsCompleted() == GetMaxDailyQuests() then RColor= 1; GColor= 0; BColor = 0; RIcon= 1; GIcon= 0; BIcon = 0; CompletedText = L["DAILIES_MAX"]
								else RColor= 0.5; GColor= 0.5; BColor = 0.5; RIcon= 0.5; GIcon= 0.5; BIcon = 0.5;

								if DailyQuestsList[index]["dates"] then
									CompletedText = DailyQuestsList[index]["dates"].starting .." - ".. DailyQuestsList[index]["dates"].ending
								else 
									CompletedText = DailyQuestsList[index]["loc"]
								end
								
								if DailyQuestsList[index]["prof"] then
									CompletedText = DailyQuestsList[index]["prof"]
									if DailyQuestsList[index]["prof"] == hasHerbalism then RColor= 0.5; GColor= 0.5; BColor = 0.5; RIcon= 0.5; GIcon= 0.5; BIcon = 0.5;
									elseif DailyQuestsList[index]["prof"] == hasMining then RColor= 0.5; GColor= 0.5; BColor = 0.5; RIcon= 0.5; GIcon= 0.5; BIcon = 0.5;
									elseif DailyQuestsList[index]["prof"] == hasSkinning then RColor= 0.5; GColor= 0.5; BColor = 0.5; RIcon= 0.5; GIcon= 0.5; BIcon = 0.5;
									else RColor= 1; GColor= 0; BColor = 0; RIcon= 1; GIcon= 0; BIcon = 0;
									end
								end
							end
							
							if index and (DailyQuestsList[index]["SID"] <= RepFactionsHolder[GroupName]) then
								cat:AddLine(
									'text', " " .. index,
									'textR', RColor,
									'textG', GColor,
									'textB', BColor,
									'indentation', 12,
									'text2', CompletedText,
									'text2R', RColor,
									'text2G', GColor,
									'text2B', BColor,
									'hasCheck', true,
									'checked', true,
									'checkIcon', DailyQuestsList[index]["icon"],
									'checkCoordLeft', 0.08,
									'checkCoordRight', 0.92,
									'checkCoordTop', 0.08,
									'checkCoordBottom', 0.92,
									'checkColorR', RIcon,
									'checkColorG', BIcon,
									'checkColorB', GIcon,
									'func', 'OnQuestClick',
									'arg1', self,
									'arg2', index
								)
							end
						end
					end
				end
				if Dailies.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] == false then cat:AddLine () end
			
			elseif self.db.char.GroupValues[DailiesGroups[GroupName]["group"]] > 0  and self.db.char.Filters[GroupName] == false then
				MinColor = Crayon:GetThresholdHexColor(self.db.char.GroupValues[DailiesGroups[GroupName]["group"]], DailiesGroups[GroupName]["ValueMax"])
				cat = Tablet:AddCategory(
					'text', DailiesGroups[GroupName]["title"],
					'textR', 1, 'textG', 0.8, 'textB', 0,
					'text2', "[" .. Crayon:Colorize(MinColor, self.db.char.GroupValues[GroupName]) .. "/" .. Crayon:Green(DailiesGroups[GroupName]["ValueMax"]) .. "]",
					'text2R', 1, 'text2G', 0.8, 'text2B', 0,
					'columns', 2,
					'showWithoutChildren', true,
					'hideBlankLine', true,
					'func', function() self.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] = not self.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] end,
					'hasCheck', true,
					'checked', true,
					'checkIcon', self.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] and "Interface\\Buttons\\UI-PlusButton-Up" or "Interface\\Buttons\\UI-MinusButton-Up"
				)
				
				for index, value in pairsByKeys (self.db.char.DailyQuestsCompleted) do
					if self.db.char.DailyQuestsObjectives[index] == L["QUEST_TURN_IN"] then RColor= 0; GColor= 1; BColor = 0; RIcon= 1; GIcon= 1; BIcon = 1; CompletedText = L["QUEST_TURN_IN"]
						elseif self.db.char.DailyQuestsCompleted[index] then RColor= 1; GColor= 1; BColor = 1; RIcon= 1; GIcon= 1; BIcon = 1; CompletedText = self.db.char.DailyQuestsCompleted[index]
						elseif self.db.char.DailyQuestsAccepted[index] then RColor= 0; GColor= 1; BColor = 0; RIcon= 1; GIcon= 1; BIcon = 1; CompletedText = L["QUEST_ACCEPTED"]
						elseif self.db.char.GroupValues[DailiesGroups[GroupName]["group"]] ==  DailiesGroups[GroupName]["ValueMax"] then RColor= 1; GColor= 0; BColor = 0; RIcon= 1; GIcon= 0; BIcon = 0; CompletedText = L["DAILIES_GROUP_MAX"]
						elseif GetDailyQuestsCompleted() == GetMaxDailyQuests() then RColor= 1; GColor= 0; BColor = 0; RIcon= 1; GIcon= 0; BIcon = 0; CompletedText = L["DAILIES_MAX"]
						else RColor= 0.5; GColor= 0.5; BColor = 0.5; RIcon= 0.5; GIcon= 0.5; BIcon = 0.5; CompletedText = DailyQuestsList[index]["prof"]
					end
					if Dailies.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] == false then		
						if DailyQuestsList[index]["group"] == GroupName then
							cat:AddLine(
								'text', " " .. index,
								'textR', RColor,
								'textG', GColor,
								'textB', BColor,
								'indentation', 12,
								'text2', CompletedText,
								'text2R', 1,
								'text2G', 1,
								'text2B', 1,
								'hasCheck', true,
								'checked', true,
								'checkIcon', DailyQuestsList[index]["icon"],
								'checkCoordLeft', 0.08,
								'checkCoordRight', 0.92,
								'checkCoordTop', 0.08,
								'checkCoordBottom', 0.92,
								'checkColorR', 1,
								'checkColorG', 1,
								'checkColorB', 1,
								'func', 'OnQuestClick',
								'arg1', self,
								'arg2', index
							)
						end
					end
				end
			end
			if Dailies.db.profile.hideDetails[DailiesGroups[GroupName]["group"]] == false then cat:AddLine () end
		end
	
	-- Spacer
	cat = Tablet:AddCategory(
		'columns', 1,
		'showWithoutChildren', true,
		'hideBlankLine', true
	)
	end

	-- Displays how many dailies are left for the day
	cat:AddLine(
		'text', AmountText,
		'justify', "CENTER"
	)
	
	-- Displays when the dailies will reset
	cat:AddLine(
		'text', DailiesText,
		'justify', "CENTER"
	)
	
	-- Tooltip DISCLAIMER
	if UnitLevel("player") < 70 then
		cat:AddLine(
			'text', L["TOOLTIP_DISCLAIMER"],
			'hasCheck', true,
			'checked', true,
			'checkIcon', "Interface\\HelpFrame\\HotIssueIcon"
		)
	end
	
	if self.db.char.HideHints == false then
		-- FuBar Left-Click HINT
		cat:AddLine(
			'text', L["FUBAR_LCLICK"],
			'textR', 0,
			'textG', 0.5,
			'textB', 0,
			'hasCheck', true,
			'checked', true,
			'checkIcon', "Interface\\GossipFrame\\AvailableQuestIcon"
		)
		
		-- Tooltip Left-Click HINT
		cat:AddLine(
			'text', L["TOOLTIP_LCLICK"],
			'textR', 0,
			'textG', 0.5,
			'textB', 0,
			'hasCheck', true,
			'checked', true,
			'checkIcon', "Interface\\GossipFrame\\AvailableQuestIcon"
		)
		
		-- Tooltip Itemlink HINT
		cat:AddLine(
			'text', L["TOOLTIP_ITEMLINK"],
			'textR', 0,
			'textG', 0.5,
			'textB', 0,
			'hasCheck', true,
			'checked', true,
			'checkIcon', "Interface\\GossipFrame\\AvailableQuestIcon"
		)
	end
end

function Dailies:OnQuestClick(QuestTitleValue)
	-- If USER is using FuBar then make the tooltips look consistant
	if LibRockFuBar == true then
		FontIconSize = FuBar.db.profile.tooltip.fontSizePercent
	else
		FontIconSize = 1
	end
	
	-- Make a new tooltip if the USER clicks on a quest title
	Dewdrop:Open(Tablet20Frame,
    'children', function()
	    Dewdrop:AddLine(
            'text', QuestTitleValue .. L["TOOLTIP_REWARDS"],
			'textHeight', FontIconSize * 12, 
			'isTitle', true,
			'icon', DailyQuestsList[QuestTitleValue]["icon"],
			'iconWidth', FontIconSize * 14,
			'iconHeight', FontIconSize * 14,
			'iconCoordLeft', 0.08,
			'iconCoordRight', 0.92,
			'iconCoordTop', 0.08,
			'iconCoordBottom', 0.92
        )
		
		-- If ITEMS are awarded, add them to the tooltip
		if DailyQuestsList[QuestTitleValue]["rewards"] then
			for Reward, RewardType in pairs(DailyQuestsList[QuestTitleValue]["rewards"]) do
			-- Grab itemlink and quantity from quest and break it apart
			local RewardType, RewardAmount = (":"):split(RewardType); RewardAmount = tonumber(RewardAmount)
			if RewardAmount < 2 then RewardAmount = "" else RewardAmount = (" x" .. RewardAmount) end
			itemName, itemLink, itemRarity, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount, itemEquipLoc, itemTexture = GetItemInfo(RewardType); 
			if itemLink == nil then GameTooltip:SetHyperlink("item:".. RewardType); end
			
			if itemLink then
		        Dewdrop:AddLine(
					'text', itemLink .. RewardAmount,
					'textHeight', FontIconSize * 12, 
					'icon', itemTexture,
					'iconWidth', FontIconSize * 14,
					'iconHeight', FontIconSize * 14,
					'iconCoordLeft', 0.08,
					'iconCoordRight', 0.92,
					'iconCoordTop', 0.08,
					'iconCoordBottom', 0.92,
					'tooltipFunc', self.SetTooltip,
					'tooltipArg1', GameTooltip, 'tooltipArg2', RewardType,
					'func', 'itemClickLink',
					'arg1', self,
					'arg2', itemLink,
					'arg3', RewardAmount
		        )
			end
			end
		end

		-- If HONOR awarded, add it to the tooltip
		if DailyQuestsList[QuestTitleValue]["honor"] then
			Dewdrop:AddLine(
				'text', "~" .. DailyQuestsList[QuestTitleValue]["honor"] .. L["TOOLTIP_HONOR_POINTS"],
				'textHeight', FontIconSize * 12, 
				'icon', BGHonor,
				'iconWidth', FontIconSize * 14,
				'iconHeight', FontIconSize * 14
	        )
		end

		-- If REPUTATION awarded, add it to the tooltip
		if DailyQuestsList[QuestTitleValue]["rep"] then
			-- Cycle through the USER's known factions and hold them in a table to see if a quest should be displayed
			for factionIndex = 1, GetNumFactions() do
				FactionName, _, standingID, _, _, earnedValue, _, _, _, _, _ = GetFactionInfo(factionIndex)
				RepFactionsHolder[FactionName] = standingID
			end
	
			for RepReward, RepRewardType in pairs(DailyQuestsList[QuestTitleValue]["rep"]) do
			-- Grab faction name and reputation from quest and break it apart
			local RepRewardType, RepAmount = (":"):split(RepRewardType)
			-- Check to see if the PLAYER is HUMAN and multiply Reputation by 10%
			if PlayerRace == "Human" then RepAmount = ceil(RepAmount + (RepAmount * .10)) else RepAmount = RepAmount end
			-- If Repuation Standing is nil then set it to UNKNOWN
			if RepFactionsHolder[RepRewardType] == nil then RepFactionsHolder[RepRewardType] = 0 end

			Dewdrop:AddLine(
				'text', Crayon:Green(RepAmount) .. L["TOOLTIP_REPUTATION"] .. Crayon:Colorize(RGBPercToHex(RepFactionColors[RepFactionsHolder[RepRewardType]].r,
																									RepFactionColors[RepFactionsHolder[RepRewardType]].g,
																									RepFactionColors[RepFactionsHolder[RepRewardType]].b ),
																									RepRewardType),
				'textHeight', FontIconSize * 12, 
				'icon', "Interface\\Icons\\INV_Misc_GroupLooking",
				'iconWidth', FontIconSize * 14,
				'iconHeight', FontIconSize * 14,
				'iconCoordLeft', 0.08,
				'iconCoordRight', 0.92,
				'iconCoordTop', 0.08,
				'iconCoordBottom', 0.92
			)
			end
		end
		
		-- If GOLD awarded, add it to the tooltip
		if DailyQuestsList[QuestTitleValue]["gold"] then
			Dewdrop:AddLine(
				'text', Abacus:FormatMoneyExtended(DailyQuestsList[QuestTitleValue]["gold"], true),
				'textHeight', FontIconSize * 12, 
				'icon', "Interface\\Icons\\INV_Misc_Coin_02",
				'iconWidth', FontIconSize * 14,
				'iconHeight', FontIconSize * 14,
				'iconCoordLeft', 0.08,
				'iconCoordRight', 0.92,
				'iconCoordTop', 0.08,
				'iconCoordBottom', 0.92
	        )
		end
		
		if self.db.char.HideHints == false then
		-- FuBar Left-Click HINT
		cat:AddLine(
			'text', L["FUBAR_LCLICK"],
			'textR', 0,
			'textG', 0.5,
			'textB', 0,
			'hasCheck', true,
			'checked', true,
			'checkIcon', "Interface\\GossipFrame\\AvailableQuestIcon"
		)
		end
		
    end
	)
	
	-- Rewards Tooltip placement
	Dewdrop20Level1:ClearAllPoints();
	if self.db.char.TooltipPlacement == "Left" then
		Dewdrop20Level1:SetPoint("TOPLEFT", GetMouseFocus():GetName(), "TOPRIGHT", 10, 30)
	else
		Dewdrop20Level1:SetPoint("TOPRIGHT", GetMouseFocus():GetName(), "TOPLEFT", -10, 30)
	end
	Dewdrop20Level1:Show();
end

-- Click on FuBar icon will toggle the Quest Log Window
function Dailies:OnClick(button)
	ToggleQuestLog();
end

-- Makes the tooltip an actual item
function Dailies:SetTooltip(arg1, arg2)
	GameTooltip_SetDefaultAnchor(GameTooltip, this)
	GameTooltip:SetHyperlink("item:"..arg1..":0:0:0:0:0:0:0")
end

-- Left-Shift-Click to paste itemlink into chatbox
function Dailies:itemClickLink(link, amount)
	if IsShiftKeyDown() then
		if not ChatFrameEditBox:IsVisible() then
			ChatFrameEditBox:Show()
		end
		ChatFrameEditBox:Insert(link .. amount)
	end
end